package com.caocao.controller;

import com.caocao.domain.AccountConst;
import com.caocao.domain.RequestResult;
import com.caocao.domain.model.TUser;
import com.caocao.service.UserService;
import com.caocao.utils.RequestResultUtil;
import com.caocao.utils.VerifyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述:用户登陆控制器
 *
 * @Author:操文健
 * @Create Time:2017-09-10 8:09
 */
@RestController
@RequestMapping(value = "/login")
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private UserService userService;

    /**
     * 用户登陆验证方法
     * @param userCode
     * @param passWd
     * @param session
     * @return
     */
    @PostMapping(value = "/userLogin")
    @ResponseBody
    public RequestResult login(@RequestParam(value = "userCode") String userCode,  @RequestParam(value = "passWd")String passWd, HttpSession session) {
   // public RequestResult login(HttpServletRequest request) {
        logger.info("开始进入用户登陆验证方法进行验证用户信息...");
        //request.getParamete();
        TUser tUser = userService.getUserForNameAndPass(userCode, passWd);
        if (VerifyUtil.isEmpty(tUser)) {
            // 如果返回的用户信息为空,则就证明用户不存在,界面返回错误信息
            return  RequestResultUtil.error("用户名/密码错误");
        }
        // 进行业务方法的调用,判断用户名密码是否正确等
        session.setAttribute(AccountConst.SESSION_USER_LOGINGO, tUser);
        return RequestResultUtil.success(tUser.getUsername());
    }

    /**
     * 用户登出界面  直接销毁session信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        logger.info("用户退出系统...");

        HttpSession session = request.getSession();
        session.setAttribute(AccountConst.SESSION_USER_LOGINGO, null);

        //response.sendRedirect(request.getContextPath() + "/static/login.html");

    }

    @RequestMapping(value = "/getUser")
    public  RequestResult getloggingUser(HttpSession session) {
        TUser user = (TUser) session.getAttribute(AccountConst.SESSION_USER_LOGINGO);
        if (VerifyUtil.isEmpty(user)) {
            return RequestResultUtil.error("当前用户未登录,sesson为空");
        } else {
            Map<String, Object> userInfo = new HashMap<String, Object>();
            userInfo.put("userId", user.getId());
            userInfo.put("userCode", user.getUsercode());
            userInfo.put("userName", user.getUsername());
            return RequestResultUtil.success(userInfo, user.getUsername());
        }
    }
}
